var root = this;
//程序主动关闭标记
root.handerClose = false
var wsMethod = (function () {
  var socket = null;
  function connect(wsurl) {
    if ('WebSocket' in root) {
      socket = new WebSocket(wsurl);
    } else if ('MozWebSocket' in root) {
      socket = new MozWebSocket(wsurl);
    } else {
      console.warn("websocket not supported ,please use chorme!")
    }
  }
  function onOpen() {
    postMessage({ code: "openConnect" });
  }
  function onClose(event) {
    postMessage({ code: "closewsconnect" });
    socket = null;
    if(root.handerClose){
      return
    }
    //断线重连
    setTimeout(function () {
      connect(event.target.url);
      initMessageEvent();
    }, 1000);
  }
  function onMessaage(event) {
    postMessage(JSON.parse(event.data));
  }
  function onError(event) {
    console.log("我这里出错")

  }
  function sendMessage(msg) {
    if (socket == null) return;
      socket.send(msg);
  }
  function updateDisplayAccident(msg){
    if (socket == null) return;
      socket.send(msg);
  }
  function initMessageEvent() {
    socket.onopen = onOpen;
    socket.onclose = onClose;
    socket.onmessage = onMessaage;
    socket.onerror = onError;
  }

  function closeWs(){
    if(socket !=null){
      socket.close()
      socket = null
    }
  }
  return {
    initWsConnect: function (url) {
      connect(url);
      initMessageEvent();
    },
    sendMessage: sendMessage,
    updateDisplayAccident:updateDisplayAccident,
    closeWs:closeWs
  }
})();

onmessage = function (event) {
  if (event.data.code) {
    var code = event.data.code.toLowerCase();
    switch (code) {
      case "init":
        postMessage({ code: "initws", msg: "正在连接websocket" });
        var url = event.data.url;
        wsMethod.initWsConnect(url);
        root.handerClose = false
        break;
      case "sendmsg":
        wsMethod.sendMessage(JSON.stringify(event.data.data));
        break;
      case "close":
        root.handerClose = true
        wsMethod.closeWs()
        break
      case "displayaccident":
        wsMethod.updateDisplayAccident(JSON.stringify(event.data.data))
        break
      default:
        console.log("我这边")
        break;
    }
  }
}
